import { Message, Modal } from '@arco-design/web-vue';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import timeGridPlugin from '@fullcalendar/timegrid';
import { defineStore } from 'pinia';
import { computed, reactive, toRefs } from 'vue';
import { getData, getDetail, saveData } from './api';
export const useClockStore = defineStore('clock', () => {
  const model = () => ({
    title: ``,
    desc: ``,
    start_time: ``,
    end_time: ``,
    score: 0,
    student_id: [],
  });

  const fetchData = async () => {
    const { data } = await getData();
    console.log(data);
    state.options.squad = data.squad;
    state.data = data.list;
  };
  fetchData();
  const state = reactive({
    data: [],
    calendarOptions: {
      plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin],
      selectable: true,
      locale: 'zh-CN',
      firstDay: 1,
      buttonText: { today: '今天' },
      weekNumbers: true,
      // navLinks: true,
      headerToolbar: {
        left: 'prev',
        center: 'title',
        right: 'today,next',
      },
      // editable: true, // 是否可以进行（拖动、缩放）修改
      eventStartEditable: true, // Event日程开始时间可以改变，默认true，如果是false其实就是指日程块不能随意拖动，只能上下拉伸改变他的endTime
      eventDurationEditable: true, // Event日程的开始结束时间距离是否可以改变，默认true，如果是false则表示开始结束时间范围不能拉伸，只能拖拽
      selectable: true, // 是否可以选中日历格
      selectMinDistance: 0, // 选中日历格的最小距离
      dayMaxEvents: true,
      weekends: true, // 是否在任何日历视图中包括周六/周日列。
      navLinks: false, // 确定日名和周名是否可单击
      schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', // 此配置是为了消除右下角的版权提示
      slotEventOverlap: false, // 相同时间段的多个日程视觉上是否允许重叠，默认true允许
      select(e) {
        state.status = true;
        state.form.start_time = e.startStr + ' 00:00:00';
        state.form.end_time = e.endStr + ' 00:00:00';
      },
      async eventClick(e) {
        console.error(e);
        const event = e.event;
        const { data } = await getDetail({ id: event.id });
        console.log(data);
        state.form = {
          ...data,
          student_id: data.student_id.split(','),
        };
        state.status = true;
      },
      // initialView: 'timeGridDay',timeGridWeek
      initialView: 'dayGridMonth',
      // resourceAreaWidth: '15%',
      events: computed(() => state.data), // 后台给 渲染的数据
    },
    value: new Date('2023-11-20'),
    change(val) {
      console.log(val);
    },
    active: 3,
    status: false,
    formRef: null,
    rules: {
      title: [{ required: true, message: '请输入任务标题' }],
      desc: [{ required: true, message: '请输入任务介绍' }],
      start_time: [{ required: true, message: '请选择任务开始时间' }],
      end_time: [{ required: true, message: '请选择任务结束时间' }],
      score: [{ required: true, message: '请输入积分奖惩' }],
      student_id: [{ required: true, message: '请选择学生' }],
    },
    options: {
      squad: [],
      student: [],
    },
    rowSelection: {
      showCheckedAll: true,
      type: 'checkbox',
    },
    selectedKeys: [],
    form: model(),
    fetchData: null,
    allAudits(status) {
      const ids = state.selectedKeys.join(',');
      if (!ids) {
        Message.warning('请选择要审核学员');
        return;
      }
      Modal.error({
        title: '操作提示',
        content: `是否确认${
          status == 3 ? '通过' : status == 4 ? '驳回' : ''
        }所选学员?`,
        async onOk() {
          await state.audits(ids, status);
        },
      });
    },
    async audits(id, status) {
      await auditsData({ id, status });
      Message.success(status == 3 ? '通过成功' : status == 4 ? '驳回成功' : '');
      state.fetchData();
    },
    async handleBeforeOk(done) {
      const vaild = !!(await state.formRef.validate());
      if (vaild) {
        done(false);
        console.error(state.form);
        return;
      }
      console.log('success', state.form);
      await saveData({
        ...state.form,
        student_id: state.form.student_id
          .filter((v) => typeof v == 'number')
          .join(','),
      });
      Message.success(state.form?.id ? '编辑成功' : '新建成功');
      state.status = false;
      fetchData();
    },
    open(focusRef, formRef) {
      focusRef.focus();
      state.formRef = formRef;
    },
    async add() {
      state.status = true;
      state.form = model();
    },
    async dels() {
      const ids = state.selectedKeys.join(',');
      console.log(ids);
      if (!ids) {
        Message.warning('请选择要删除的学员');
        return;
      }
      Modal.error({
        title: '操作提示',
        content: '是否确认删除所选学员?',
        async onOk() {
          await state.del(ids);
        },
      });
    },
    async del(id) {
      await delData(id);
      Message.success('删除成功');
      state.fetchData();
    },
    edit(record) {
      console.log(record);
      Object.assign(state.form, {
        ...record,
      });
      state.status = true;
    },
  });
  return {
    ...toRefs(state),
  };
});

export default useClockStore;
